/*
 * 按换行符分割data数据
 * @param: nameStr [string]
 * @param: chineseNameStr [string]
 */
function splitDataStr(nameStr, chineseNameStr) {
  const name = nameStr.trim().split(/[\r\n]/g)
  const chineseName = chineseNameStr.trim().split(/[\r\n]/g)
  return { name, chineseName }
}

//去除字符串内所有的空格
export function trim(str) {
  return str.replace(/\s*/g, '')
}

/*
 * 包装数据为Json数组
 * @param: name [array]
 * @param: chineseName [array]
 * @param: lang [array]
 */
export function handleDataStr(nameStr, chineseNameStr) {
  const { name, chineseName } = splitDataStr(nameStr, chineseNameStr)
  let ret = []
  let len = name.length
  for (let i = 0; i < len; i++) {
    ret.push({
      name: trim(name[i]),
      chineseName: trim(chineseName[i])
    })
  }
  return ret
}

/*
 * 二位数组转一维数组
 * @param: name [array]
 */
export function flat(arr) {
  return arr.reduce((pre, value) => {
    return Array.isArray(value) ? [...pre, ...flat(value)] : [...pre, value]
  }, [])
}

/*
 * 数组去重
 * @param: [array]
 */
export function unique(arr) {
  return Array.from(new Set(arr))
}

/*
 * JSON数组去重
 * @param: [array] json Array
 */
export function uniqueJsonArray(array) {
  let arr = [...array]
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; ) {
      if (arr[i].name == arr[j].name) {
        arr.splice(j, 1)
      } else j++
    }
  }
  return arr
}

//复制到粘贴板
export function copyToClipboard(text, vm) {
  var textArea = document.createElement('textarea')
  textArea.style.position = 'fixed'
  textArea.style.top = '0'
  textArea.style.left = '0'
  textArea.style.padding = '0'
  textArea.style.border = 'none'
  textArea.style.outline = 'none'
  textArea.style.boxShadow = 'none'
  textArea.style.background = 'transparent'
  textArea.value = text
  document.body.appendChild(textArea)
  textArea.select()
  try {
    var successful = document.execCommand('copy')
    var msg = successful ? '成功复制到剪贴板' : '该浏览器不支持点击复制到剪贴板'
    vm && vm.$message.success(msg)
  } catch (err) {
    vm && vm.$message.error('该浏览器不支持点击复制到剪贴板')
  }
  document.body.removeChild(textArea)
}
